import { api } from '@/service/net/server-api'
import type { DrawParams } from '@/service/types'
import { useAutoRequest } from '@alova/scene-vue'
import { useRequest } from 'alova'

const useDrawable = (drawData: DrawParams) => {
  const loading = ref(true)
  const { data: performData, onSuccess: onPerformDrawSuccess } = useRequest(
    () => api.performDraw(drawData),
    {
      immediate: true
    }
  )
  const {
    data: drawResult,
    onSuccess: onProcessQuerySuccess,
    send: queryDrawProcess,
    abort: abortQueryDrawProcess
  } = useAutoRequest(() => api.queryDrawProcess(performData.value.draw_request_id), {
    immediate: false,
    force: true,
    /**
     * 浏览器显示隐藏触发
     * @default true
     */
    enableVisibility: true,

    /**
     * 浏览器聚焦触发
     * @default true
     */
    enableFocus: true,

    /**
     * 网络重连触发
     * @default true
     */
    enableNetwork: true,

    /**
     * 节流时间，在一定时间内多次触发只会发送1次请求，单位ms
     * @default 1000
     */
    throttle: 1000,
    /**
     * 轮询请求的时间，设置大于0时有效，单位ms
     * @default 0
     */
    pollingTime: 1000
  })
  /** 发起渲染请求成功回调 */
  onPerformDrawSuccess(() => {
    queryDrawProcess()
  })
  /** 查询渲染进度成功回调 */
  onProcessQuerySuccess(() => {
    console.log('查询渲染进度', drawResult.value.draw_status)
    if (drawResult.value.draw_status === 'SUCCEED') {
      loading.value = false
      // 渲染成功，停止轮询
      console.log('中断请求')
      abortQueryDrawProcess()
    }
  })

  return { loading, drawResult }
}
export default useDrawable
